<?php

namespace App\Exceptions;

use App\Logging\Service\LogService;
use App\Services\CommonService;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        ApiException::class,
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    public function report(\Throwable $e)
    {
        // 检查并回滚事务
        if (DB::transactionLevel() > 0) {
            while (DB::transactionLevel() > 1) {
                DB::rollBack(); // 回滚嵌套事务
            }
            DB::rollBack(); // 回滚最外层事务
        }

        if ($e instanceof ApiErrorException) {
            $logLevel = $e->getLogLevel();
            Log::$logLevel($e->getMessage(), ['content' => $e->getContext(), 'trace' => $e->getTrace()]);
        } else {
            parent::report($e);
        }
    }

    public function render($request, \Throwable $e)
    {
        if (App::runningInConsole()) {
            return parent::render($request, $e);
        }

        if ($e instanceof NotFoundHttpException) {
            return Response::json(['status' => CommonService::HTTP_CODE_FAIL, 'msg' => "Http Not Found"]);
        }

        if ($e instanceof ApiException) {
            return Response::json(['status' => $e->getCode(), 'msg' => $e->getMessage(), 'data' => $e->getData()]);
        }

        if ($e instanceof ApiErrorException) {
            $data = [
                'status' => $e->getCode(),
                'msg' => $e->getMessage(),
                'traceId' => LogService::getInstance()->getFinalTraceId(),
                'data' => method_exists($e, 'getData') ? $e->getData() : [],
            ];
            if (config('app.debug')) {
                $data['trace'] = $e->getTrace();
            }
            return Response::json($data)->header('Content-type', 'application/json; charset=utf-8');
        }

        $data = [
            'status' => CommonService::HTTP_CODE_FAIL,
            'msg' => $e->getMessage(),
            'traceId' => LogService::getInstance()->getFinalTraceId(),
            'data' => method_exists($e, 'getData') ? $e->getData() : [],
        ];
        if (config('app.debug')) {
            $data['trace'] = $e->getTrace();
        }
        return Response::json($data);
    }
}
